#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:dell

#涨停股分时图主文件,运行此文件可以得到绘制分时图的界面.

import datetime
from gm.api import *
import sys
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import pyqtgraph as pg
import pandas as pd
from ticks import Ui_MainWindow
import getdata
set_token('df082f274b3ee380fcd2a98a2e5a7217dac1268b')


class MyThread(QThread):
    my_signal = pyqtSignal(str)

    def __init__(self):
        super(MyThread, self).__init__()
        self.count = False

    def run(self):
        get = getdata.GetData()
        get.daily_ts()
        get.turn_gm()
        get.instruments()

    def get_d(self, current):
        data = history(current['symbol'], 'tick', current['trade_date'] + ' 09:24:00',
                       current['trade_date'] + ' 15:00:00', fields=None, adjust=ADJUST_PREV, df=True)
        if not data.empty:
            del data['quotes'], data['open'], data['high'], data['low'], data['last_volume'], data['last_amount']
            data[['cum_volume']] = (data['cum_volume'] / 100).astype('uint64')
            data['cum_amount'] = data['cum_amount'].astype('uint64')
            # data['now_turn'] = data['cum_volume'] / data['ytd_v'] * data['ytd_t']
            data['created_at'] = data['created_at'].astype('datetime64[ns]') + datetime.timedelta(hours=8)
            data.to_hdf('D:/data/ticks.h5', current['trade_date'], mode='a')
            data['created_at'] = data['created_at'].dt.time.astype('str').apply(lambda x: x.split(' ')[0])
            data = data[data['created_at'] >= '09:30'].reset_index()
        else:
            pass
        return data

    def get_minutes(self, current):
        data = history(current['symbol'], '60s', current['trade_date'] + ' 09:24:00',
                       current['trade_date'] + ' 15:00:00', fields=None, adjust=ADJUST_PREV, df=True)

class MyGraphWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MyGraphWindow, self).__init__()
        self.setupUi(self)  # 初始化窗口
        self.lastdate.clicked.connect(self.LastDateClicked)
        self.nextdate.clicked.connect(self.NextDateClicked)
        self.lineEdit.textChanged.connect(self.onlineEditTextChanged)
        # self.nextsymbol.clicked.connect(self.plot_slot)
        self.nextsymbol.clicked.connect(self.next_symbol_clicked)
        self.lastsymbol.clicked.connect(self.last_symbol_clicked)
        # self.lastsymbol.clicked.connect(self.plot_slot)
        self.save.clicked.connect(self.save_buy)
        self.sell.clicked.connect(self.save_sell)
        self.lasttick.clicked.connect(self.last_tick_plot)
        self.nexttick.clicked.connect(self.next_tick_plot)
        self.dates = self.get_list()
        self.my_thread = MyThread()
        self.n = 0
        self.symbol_index = 0
        self.last_cilck = 0
        self.jump = False
        self.all = pd.read_hdf('D:/data/limit_up.h5', 'limit_up')
        self.all_date = self.all['trade_date'].drop_duplicates().dt.date.astype('str').tolist()
        self.all = self.all[(self.all['o_pct'] >= 0.05) & (self.all['y_turn'] >= 10) & (self.all['ybs'] > 0) & (
                self.all['o_l'] == False)]
        self.all = self.all[(self.all['y_turn'] <= 15) & (self.all['ybs'] < 5)]
        self.data = 0
        self.pl = self.set_graph_ui()
        self.get_last = {}
        self.operation = []
        self.FN = MyThread()
        self.getdata.clicked.connect(self.start_func)

    def start_func(self):
        self.FN.start()

    def set_graph_ui(self):
        pg.setConfigOptions(antialias=True)  # pg全局变量设置函数，antialias=True开启曲线抗锯齿
        self.win = pg.GraphicsLayoutWidget()  # 创建pg layout，可实现数据界面布局自动管理
        # pg绘图窗口可以作为一个widget添加到GUI中的graph_layout，当然也可以添加到Qt其他所有的容器中
        '''
        self.symbols = self.data_date['symbol'].drop_duplicates().tolist()
        self.data = self.data_date[self.data_date['symbol'] == self.symbols[self.symbol_index]]
        self.data['created_at'] = self.data['created_at'].dt.time
        self.data['created_at'] = self.data['created_at'].copy().astype('str').apply(lambda x:x.split('.')[0].split(':')[0]+':'+x.split('.')[0].split(':')[1])
        self.data = self.data[self.data['created_at'] >= '09:30'].reset_index()
        self.btm = self.data['created_at']
        self.dict = dict(enumerate(self.btm))
        self.axis = [(i, list(self.btm)[i]) for i in range(0, len(self.btm), 600)]
        self.stringaxis = pg.AxisItem(orientation='bottom')
        self.stringaxis.setTicks([self.axis, self.dict.items()])
        df = pd.read_hdf('D:/data/limit_up.h5', 'limit_up', where=["symbol='"+self.symbols[self.symbol_index]+"'", "trade_date='"+self.dates[self.n]+"'"])
        df = df.iloc[0]
        self.data['upper_limit'], self.data['pre_close'] = df['upper_limit'], round(df['pre_close'], 2)
        self.lft = round(self.data['price']/self.data['pre_close']-1, 2)
        self.dic = dict(enumerate(self.lft))
        self.axi = [(i, list(self.lft)[i]) for i in range(0, len(self.lft), 1)]
        self.stringaxi = pg.AxisItem(orientation='left')
        self.stringaxi.setTicks([self.axi, self.dic.items()])
        '''
        self.verticalLayout.addWidget(self.win)
        pl = self.win.addPlot(title="ticks")  # , axisItems={'bottom': self.stringaxis})  # 添加第一个绘图窗口
        pl.setLabel('left', text='price', color='#ffffff')  # y轴设置函数
        pl.showGrid(x=True, y=True)  # 栅格设置函数
        pl.setLogMode(x=False, y=False)  # False代表线性坐标轴，True代表对数坐标轴
        pl.setLabel('bottom', text='time', units='m')  # x轴设置函数
        '''
        self.l_time = ['09:30', '10:00', '10:30', '11:00', '11:30', '13:00', '13:30', '14:00', '14:30', '15:00']
        self.s = pd.Series(self.l_time)
        self.dic = dict(enumerate(self.l_time))
        self.axis = [(i, self.s[i]) for i in range(0, len(self.s), 1)]
        self.stringaxis = pg.AxisItem(orientation='bottom')
        self.stringaxis.setTicks([self.dic.items()])
        self.verticalLayout.addWidget(self.win)
        pl = self.win.addPlot(title="ticks", axisItems={'bottom': self.stringaxis})  # 添加第一个绘图窗口
        pl.setLabel('left', text='price', color='#ffffff')  # y轴设置函数
        pl.showGrid(x=True, y=True)  # 栅格设置函数
        pl.setLogMode(x=False, y=False)  # False代表线性坐标轴，True代表对数坐标轴
        pl.setLabel('bottom', text='time', units='m')  # x轴设置函数

        pl.addLegend()  # 可选择是否添加legend
        win.nextRow()  # layout换行，采用垂直排列，不添加此行则默认水平排列
        p2 = win.addPlot(title="cos 函数")
        p2.setLabel('left', text='meg', color='#ffffff')
        p2.showGrid(x=True, y=True)
        p2.setLogMode(x=False, y=False)
        p2.setLabel('bottom', text='time', units='s')
        # p2.addLegend()
        '''
        return pl

    def get_list(self):
        store = pd.HDFStore('D:/data/ticks.h5')
        l = [x.split('/', 1)[1] for x in store.keys()]
        store.close()
        self.label.setText("data ready!")
        return l

    def LastDateClicked(self):
        if self.jump:
            self.symbol_index = 0
            index = self.n - 2
            date = self.dates[index]
            df = pd.read_hdf('D:/data/ticks.h5', date)
            self.label.setText(str(date))
            self.data_date = df
            # self.n += -1
            self.jump = False
        else:
            self.symbol_index = 0
            index = self.n - 1
            date = self.dates[index]
            df = pd.read_hdf('D:/data/ticks.h5', date)
            self.label.setText(str(date))
            self.data_date = df
            self.n += -1

    def NextDateClicked(self):
        if self.jump:
            self.symbol_index = 0
            index = self.n
            date = self.dates[index]
            df = pd.read_hdf('D:/data/ticks.h5', date)
            self.label.setText(date)
            self.data_date = df
            self.jump = False
            # self.n += 1
        else:
            self.symbol_index = 0
            index = self.n + 1
            date = self.dates[index]
            df = pd.read_hdf('D:/data/ticks.h5', date)
            self.label.setText(date)
            self.data_date = df
            self.n += 1

    def last_symbol_clicked(self):
        if not self.jump:
            self.symbol_index += -1
        else:
            self.n += -1
            self.symbol_index = 0
        self.plot_slot()

    def next_symbol_clicked(self):
        if not self.jump:
            self.symbol_index += 1
        else:
            self.n += 1
            self.symbol_index = 0
        self.plot_slot()

    def plot_slot(self):
        self.get_last = {}
        self.pl.clear()
        all = self.all[self.all['trade_date'] == self.dates[self.n]]
        symbols = all['symbol'].drop_duplicates().tolist()
        data = pd.read_hdf('D:/data/ticks.h5', self.dates[self.n])
        try:
            # data = data[data['cum_amount'] > 0].reset_index()
            df = all[all['symbol'] == symbols[self.symbol_index]]
            df = df.iloc[0]
            data = data[data['symbol'] == symbols[self.symbol_index]]
            if not data.empty:
                data['created_at'] = data['created_at'].dt.time.astype('str').apply(lambda x: x.split(' ')[0])
            else:
                current = self.get_last
                data = self.my_thread.get_d(current)
            data = data[data['created_at'] >= '09:30'].reset_index()
            data['upper_limit'], data['pre_close'] = df['upper_limit'], round(df['pre_close'], 2)
            self.plot_lasttick(data, df)
            self.jump = False
        except IndexError:
            '''
            self.symbol_index = 0
            self.n += 1
            df = pd.read_hdf('D:/data/ticks.h5', self.dates[self.n])
            self.data_date = df
            '''
            # self.get_last = []
            self.label.setText(self.dates[self.n] + ' 已没有合适的标的!点击将自动切换!')
            self.jump = True

    def save_buy(self):
        s = self.get_last['symbol']
        d = self.get_last['trade_date']
        b = -self.get_last['open']
        dic = {'symbol':s, 'trade_date':d, 'b_s':b}
        self.operation.append(dic)
        print(pd.DataFrame(self.operation)['b_s'].sum)
        self.label.setText(s + str(d) + ' 已保存！')

    def save_sell(self):
        s = self.get_last['symbol']
        d = self.get_last['trade_date']
        b = self.get_last['close']
        dic = {'symbol': s, 'trade_date': d, 'b_s': b}
        self.operation.append(dic)
        print(pd.DataFrame(self.operation)['b_s'].sum)
        self.label.setText(s + str(d) + ' 已保存！')

    def plot_lasttick(self, data, df):
        self.pl.setXRange(0, len(data), padding=0)
        self.pl.setYRange(df['pre_close'] * 0.9 / df['pre_close'] - 1, df['upper_limit'] / df['pre_close'] - 1)
        # self.pl.hideAxis('left')
        pl = self.pl
        pl.plot(data['pre_close'] / data['pre_close'] - 1, pen='r', clear=False)
        pl.plot(data['upper_limit'] / data['pre_close'] - 1, pen='r', clear=False)
        pl.plot(data['pre_close'] * 0.9 / data['pre_close'] - 1, pen='r', clear=False)
        pl.plot(data['price'] / data['pre_close'] - 1, pen='g', clear=False)
        # return df['symbol'], df['trade_date'], df['ybs'], df['o_pct'], df['y_turn']
        self.label.setText(
            df['symbol'] + ' ' + str(df['trade_date']).split(' ')[0] + ' ybs:' + str(df['ybs']) + ' o_pct:'
            + str(df['o_pct']) + ' ytn:' + str(round(df['y_turn'], 2)))
        self.get_last = {}
        self.get_last['symbol'] = df['symbol']
        self.get_last['trade_date'] = str(df['trade_date']).split(' ')[0]
        self.get_last['open'] = df['open']
        self.get_last['close'] = df['close']

    def fix_data(self, current, all):
        if current:
            if current['trade_date'] not in self.dates:
                print('需要下载..')
                self.label.setText('开始下载...')
                data = self.my_thread.get_d(current)
                if not data.empty:
                    df = all[all['symbol'] == current['symbol']]
                    df = df.iloc[0]
                    data['upper_limit'], data['pre_close'] = df['upper_limit'], round(df['pre_close'], 2)
                    self.plot_lasttick(data, df)
                else:
                    self.label.setText('超出提供数据范围...')
            elif current['trade_date'] <= self.dates[self.n]:
                print('有日期数据')
                df = all[all['symbol'] == current['symbol']]
                df = df.iloc[0]
                data = pd.read_hdf('D:/data/ticks.h5', current['trade_date'])
                data = data[data['symbol'] == current['symbol']]
                if not data.empty:
                    data['created_at'] = data['created_at'].dt.time.astype('str').apply(lambda x: x.split(' ')[0])
                    data = data[data['created_at'] >= '09:30'].reset_index()
                    data['upper_limit'], data['pre_close'] = df['upper_limit'], round(df['pre_close'], 2)
                    self.plot_lasttick(data, df)
                else:
                    print('有日期数据,但symbol数据没有')
                    data = self.my_thread.get_d(current)
                    try:
                        data = data[data['created_at'] >= '09:30'].reset_index()
                        data['upper_limit'], data['pre_close'] = df['upper_limit'], round(df['pre_close'], 2)
                        self.plot_lasttick(data, df)
                    except KeyError:
                        self.label.setText('超出数据库提供的日期!')

            else:
                print('没有日期数据!')
                # date = get_previous_trading_date(exchange='SZSE', date=current['trade_date'])
                print('从数据库读取...')
                df = all[all['symbol'] == current['symbol']]
                print(df)
                df = df.iloc[0]
                data = pd.read_hdf('D:/data/ticks.h5', current['trade_date'])
                data = data[data['symbol'] == current['symbol']]
                if not data.empty:
                    data['created_at'] = data['created_at'].dt.time.astype('str').apply(lambda x: x.split(' ')[0])
                    data = data[data['created_at'] >= '09:30'].reset_index()
                    data['upper_limit'], data['pre_close'] = df['upper_limit'], round(df['pre_close'], 2)
                    self.plot_lasttick(data, df)
                if data.empty:
                    print('从网络下载...')
                    data = self.my_thread.get_d(current)
                    try:
                        data = data[data['created_at'] >= '09:30'].reset_index()
                        df = all[all['symbol'] == current['symbol']]
                        df = df.iloc[0]
                        data['upper_limit'], data['pre_close'] = df['upper_limit'], round(df['pre_close'], 2)
                        self.plot_lasttick(data, df)
                    except KeyError:
                        self.label.setText('超出数据库提供的日期!')
        else:
            self.label.setText('没有指定标的！')

    def last_tick_plot(self):
        self.pl.clear()
        current = self.get_last
        current['trade_date'] = self.all_date[self.all_date.index(current['trade_date']) - 1]
        print(current)
        all = pd.read_hdf('D:/data/limit_up.h5', 'limit_up', where="trade_date='" + current['trade_date'] + "'")
        all['trade_date'] = all['trade_date'].dt.date.astype('str')
        self.fix_data(current, all)

    def next_tick_plot(self):
        self.pl.clear()
        current = self.get_last
        current['trade_date'] = self.all_date[self.all_date.index(current['trade_date']) + 1]
        print(current)
        all = pd.read_hdf('D:/data/limit_up.h5', 'limit_up', where="trade_date='" + current['trade_date'] + "'")
        print(all)
        all['trade_date'] = all['trade_date'].dt.date.astype('str')
        self.fix_data(current, all)

    def onlineEditTextChanged(self, p_str):
        p_str = 'sucess!'
        self.label.setText(p_str)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myWin = MyGraphWindow()
    myWin.show()
    sys.exit(app.exec_())
